package com.powernode.aspect;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.powernode.domain.SysLog;
import com.powernode.service.SysLogService;
import com.powernode.util.AuthUtils;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;

/**
 * @create: 2024/7/17
 * @author: gyhe10
 * @description: 记录系统操作日志AOP
 **/

@Component
@Aspect
@Slf4j
public class SysLogAspect {

    @Resource
    private SysLogService sysLogService;

    /**
     * 记录系统操作日志的切入点表达式
     */
    public static final String POINT_CUT = "execution(* com.powernode.controller.*.*(..))";

    @Around(value = POINT_CUT)
    public Object logAround(ProceedingJoinPoint joinPoint) {
        Object result = null;
        // 获取请求对象
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        // 获取请求接口路径
        String path = request.getRequestURI();

        // 获取IP地址
        String remoteHost = request.getRemoteHost();

        // 获取请求参数
        Object[] args = joinPoint.getArgs();

        // 获取请求方法
        // 通过切入点获得方法签名
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        String methodName = method.toString();

        // 获取方法描述，也就是方法上的@ApiOperation注解的value属性
        ApiOperation apiOperation = method.getDeclaredAnnotation(ApiOperation.class);
        // 判断获得的注解对象是否为空
        String operation = "";
        if (ObjectUtil.isNotNull(apiOperation)) {
            // 获取apiOperation注解的value属性
            operation = apiOperation.value();
        }

        String finalArgs = "";
        // 判断请求参数类型
        // 判断数组、集合时不仅要判断是否为null，还要判断是否有元素
        if (ObjectUtil.isNotNull(args) && args.length != 0 && args[0] instanceof MultipartFile) {
            // 说明当前请求参数为文件对象
            finalArgs = "file";
        } else {
            finalArgs = JSONObject.toJSONString(apiOperation);
        }

        // 记录开始时间
        long startTime = System.currentTimeMillis();

        try {
            // 执行方法
            result = joinPoint.proceed(args);
        } catch (Throwable e) {
            throw new RuntimeException(e);
        }

        // 记录结束时间
        long endTime = System.currentTimeMillis();
        // 方法执行时长
        long execTime = endTime - startTime;

        log.info("调用时间：{}，请求接口路径：{}，请求IP地址：{}，方法名称：{}，执行时长：{}，方法描述：{}",
                new Date(),
                path,
                remoteHost,
                methodName,
                execTime,
                operation);

        // 保存系统操作日志到数据库
        SysLog sysLog = new SysLog();
        // 获取执行系统命令的管理员ID
        Long userId = AuthUtils.getLoginUserId();
        sysLog.setUserId(userId);
        sysLog.setOperation(operation);
        sysLog.setMethod(methodName);
        sysLog.setParams(finalArgs);
        sysLog.setTime(execTime);
        sysLog.setIp(remoteHost);
        sysLog.setCreateDate(new Date());
        sysLogService.save(sysLog);

        return result;
    }
}
